
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <assert.h>
//#include <gc_allocator.h>

#include "Boolean.h"
#include "Completion.h"
#include "Expression.h"
#include "IfStatement.h"
#include "Null.h"
#include "Value.h"

IfStatement::IfStatement(Expression* expression, Statement* statement)
    : m_expression(expression), m_statement(statement)
{}

Value* IfStatement::execute_internal(Scope* scope) const
{
    // Ecma 12.5
    // 1. Evaluate expression
    // 2. Call getValue on it
    // 3. Call toBoolean on it
    Value* val_exp = m_expression->evaluate(scope)->getValue();
    CHECK_EXCEPTION(val_exp);
    Boolean* exp = val_exp->toBoolean();

    // 4. If it's false, return (normal, empty, empty)
    if (!exp->isTrue())
    {
        return new Completion(CT_NORMAL, Null::null, Completion::empty);
    }

    // 5. Evaluate statement.
    // 6. Return the result
    return m_statement->execute(scope);
}

void IfStatement::getDeclaredVariables(std::vector<String*>& ids) const
{
    m_statement->getDeclaredVariables(ids);
}

